package com.heima.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.heima.ssm.pojo.Product;
import com.heima.ssm.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.List;

/**
 * @author Penguin
 * @create Date 2021/4/30  Time 15:41
 */

@Controller
@RequestMapping("product")
public class ProductController {

    @Autowired
    private IProductService productService;

    /**
     * 显示product页面内所有产品信息，并进行分页处理
     * @return
     */
    @RequestMapping("findAll")
//    @RolesAllowed("ADMIN")
//    @Secured("ADMIN")//不屑ROLE_ADMIN会导致所有有ADMIN角色的人也无权限访问
    @Secured("ROLE_ADMIN")
    public ModelAndView findAll(@RequestParam(name = "page",required = true,defaultValue = "1")int page,
                                @RequestParam(name = "pageSize",required = true,defaultValue = "4")int pageSize){
        ModelAndView mv = new ModelAndView();
        List<Product> productList = productService.findAll(page,pageSize);
        PageInfo pageInfo = new PageInfo(productList);
        mv.addObject("pageInfo",pageInfo);
        mv.setViewName("product-list-pagehelper");
        return mv;
    }

    /**
     * 新增一个产品，并返回到findAll查询页面
     * @param product
     * @return
     */
    @RequestMapping("save")
    public String saveProduct(Product product){
        productService.save(product);
        return "redirect:findAll";
    }
}
